<script lang="jsx" setup>
import { ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import Modal from '@/components/common/modal.vue';
import { downLoadExcel } from '@/service/api/api';
import { useAntdForm, useFormRules } from '@/hooks/common/form';

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => false
  }
});

const { createRequiredRule } = useFormRules();
const { formRef, validate } = useAntdForm();

const emit = defineEmits(['close', 'downloadSuccess']);
const modelVisible = ref(props.visible);
const loading = ref(false);
const model = ref({
  date: null
});

const rules = {
  date: createRequiredRule('请选择时间')
};

function handleClose() {
  modelVisible.value = false;
  model.value.date = null;
  emit('close');
}
function getYearMonth(dateString) {
  console.log('dateString :>> ', dateString);
  // 使用正则表达式或者 split 方法来分割日期字符串
  const parts = dateString.split('-');
  // 提取年份和月份
  const year = Number.parseInt(parts[0], 10);
  const month = Number.parseInt(parts[1], 10);

  // 格式化输出
  return `${year}年${month}月`;
}

async function handleOk() {
  await validate();
  loading.value = true;
  const fileName = `${getYearMonth(model.value.date)}产值表${dayjs().format('YYYY-MM-DD HH:mm:ss')}.xlsx`;
  downLoadExcel(
    '/qms/agv/ProductionDaily/exportDaliyExcel',
    {
      time: model.value.date
    },
    fileName
  ).finally(() => {
    loading.value = false;
  });
}

watch(
  () => props.visible,
  val => {
    modelVisible.value = val;
  }
);
</script>

<template>
  <Modal
    v-model:visible="modelVisible"
    title="导出产值表"
    height="210px"
    width="568px"
    :destroy-on-close="true"
    @close="handleClose"
  >
    <div class="down-form h-full w-full flex-center">
      <AForm ref="formRef" :label-col="{ lg: 8, xs: 4 }" label-wrap :model="model" class="w-full" :rules="rules">
        <AFormItem name="date" label="时间" :label-col="{}">
          <ADatePicker v-model:value="model.date" placeholder="请选择时间" value-format="YYYY-MM-DD" class="w-full" />
        </AFormItem>
      </AForm>
    </div>

    <template #footer>
      <div class="modal-footer">
        <AButton type="primary" :loading="loading" @click="handleOk">导 出</AButton>
        <AButton @click="handleClose">关 闭</AButton>
      </div>
    </template>
  </Modal>
</template>

<style></style>
